package cn.aws360.boot.data.starter.config;

import cn.aws360.boot.data.api.factory.DruidFactory;
import cn.aws360.boot.data.api.pojo.properties.DruidProperties;
import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import lombok.RequiredArgsConstructor;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;

import javax.sql.DataSource;

/**
 * @author junnan
 */
@Configuration
@RequiredArgsConstructor
@Import(DataAutoConfiguration.class)
@AutoConfigureBefore(DataSourceAutoConfiguration.class)
@ConditionalOnMissingBean(DataSource.class)
public class DruidDataSourceAutoConfiguration {

    private final DruidProperties druidProperties;

    @Bean
    public DruidDataSource druidDataSource() {
        return DruidFactory.createDruidDataSource(druidProperties);
    }

    @Bean
    public ServletRegistrationBean<StatViewServlet> statViewServletRegistrationBean() {
        return DruidFactory.createServletRegistrationBean(druidProperties);
    }

    @Bean
    public FilterRegistrationBean<WebStatFilter> webStatFilterRegistrationBean() {
        return DruidFactory.createFilterRegistrationBean(druidProperties);
    }

    @Bean
    @SuppressWarnings("ALL")
    public FilterRegistrationBean removeDruidAdFilterRegistrationBean() {
        return DruidFactory.removeDruidAdFilterRegistrationBean(druidProperties);
    }

}
